/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package comunicacao;

import java.util.logging.Level;
import java.util.logging.Logger;
import main.DataWatcherRunnable;
import main.GestorZooKeeperBase;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;

/**
 *
 * @author Leonardo Lino
 */
public class GestorZooKeeper2 extends GestorZooKeeperBase {

    private static boolean SHOW_ERROR = false;

    public GestorZooKeeper2(String ip, int port) {
        thisAddress = ip;
        thisPort = port;
    }

    public void start() {
        try {
            Stat ready = zk.exists("/Ready", null);

            if (ready == null) {
                zk.create("/Ready",
                        null,
                        ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT);
            }

            Stat appServers = zk.exists("/AppServers", null);

            if (appServers == null) {
                initialSetup();
            } else {
                addNewServer();
            }

            DataWatcherRunnable data = new DataWatcherRunnable(zk);
            data.run();

        } catch (KeeperException ex) {
            if (SHOW_ERROR) {
                Logger.getLogger(GestorZooKeeper.class.getName()).log(Level.SEVERE, null, ex);
                errorMsg = ex.toString();
            }
        } catch (InterruptedException ex) {
            if (SHOW_ERROR) {
                Logger.getLogger(GestorZooKeeper.class.getName()).log(Level.SEVERE, null, ex);
                errorMsg = ex.toString();
            }
        }
    }

    private void initialSetup() throws KeeperException, InterruptedException {

        zk.create("/AppServers",
                null,
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);

        znodeName = "App1";

        byte[] dataArray = (thisAddress + ":" + thisPort).getBytes();
        create("AppServers/" + znodeName, dataArray);

        byte[] count = Integer.toString(1).getBytes();

        zk.create("/AppServersConfig/Counter",
                count,
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);

        Stat appReady = zk.exists("/Ready/Appready", null);
        if (appReady == null) {

            byte[] data2 = (thisAddress + ":" + thisPort).getBytes();

            create("Ready/Appready", data2);
        }

    }

    private void addNewServer() throws KeeperException, InterruptedException {

        int counter = 0;
        Stat stat = zk.exists("/AppServersConfig/Counter", null);
        byte[] dados = zk.getData("/AppServersConfig/Counter", null, stat);

        Stat appReady = zk.exists("/Ready/Appready", null);
        if (appReady == null) {
            byte[] data2 = (thisAddress + ":" + thisPort).getBytes();
            create("Ready/Appready", data2);
            counter = 1;

        } else {

            String s = new String(dados);
            counter = Integer.parseInt(s);
            counter++;
        }

        znodeName = "App" + counter;
        byte[] dataArray = (thisAddress + ":" + thisPort).getBytes();
        create("AppServers/" + znodeName, dataArray);

        zk.setData("/AppServersConfig/Counter", Integer.toString(counter).getBytes(), -1);

    }

}
